Repository navigation
fix(pages-router): give useRouter() the new route on the first render after a client navigation - #4749
Conversation
… after a client navigation
|
clanky review |
|
/bigbonk review for issues |
@vinext/cloudflare
create-vinext-app
@vinext/types
vinext
@cloudflare/workers-response-store
commit: |
|
|
Review: 1 finding. Posted 1 actionable inline finding about uncommitted popstate state leaking into router snapshots. |
Performance benchmarksCompared 1 improved · 0 regressed · 6 within ±1.5%
View detailed results and traces 🟢 improvement · 🔴 regression · ⚫ change below 1.5% · paired base/head |
|
/bigbonk review for issues |
|
Review: 1 finding. Posted 1 actionable inline finding about the completion listener overwriting the committed router snapshot. |
|
/bigbonk review for issues |
|
Since last review: 1 resolved, 0 still open, 1 new. Posted 1 actionable inline finding about the event marker failing across duplicate |
|
/bigbonk review for issues |
|
LGTM! |
|
This pull request was not reviewed automatically because it was opened by a bot. A maintainer with write access can start a review by commenting |
|
clanky review |
Fixes #4748
After a client-side navigation in the Pages Router, the destination page's first render got the previous route from
useRouter():query,pathnameandasPathwere still the ones from the page you left, thoughwindow.locationhad already changed. The right values only arrived on a second render, aftervinext:navigatefired. Next.js gives the new page the new route on its first render:Router#set()assignsthis.statebefore callingthis.sub(...)to render (packages/next/src/shared/lib/router/router.ts,set(state, data, resetScroll); checked in the installednext@16.2.7,dist/shared/lib/router/router.js).Root cause
PagesRouterProvider(packages/vinext/src/shims/router.ts) kept the route snapshot inuseState(getRouterSnapshot)and refreshed it only from thevinext:navigatelistener and the ready timer. Both navigation render paths (renderPagesNavigationTargetfor the data endpoint, and the HTML path innavigateClientHtml) commit history andwindow.__NEXT_DATA__and then callroot.render()throughrenderPagesRouterElement. The provider element keeps its type, so React keeps its state, and the page renders with the old snapshot.dispatchNavigateEvent()only runs after that render has committed.Fix
This mirrors
Router#set(), which assignsthis.statefor every router state change (full, shallow and hash-only) before anything renders from it. The provider only ever shows a committed snapshot, never the livelocation.commitRouterSnapshot()storesrouterRuntimeState.committedRouterSnapshot: the snapshot and a token that grows by one per commit. It is called where the router state changes:renderPagesRouterElement, right beforeroot.render(), once the history entry and__NEXT_DATA__are committed (push, replace and popstate, data and HTML paths);PagesRouterProvideradopts that snapshot when its token is newer than the one in its state, callingsetStateduring render before any child reads the context. Thevinext:navigatelistener adopts it the same way, so a render-backed navigation's snapshot, already adopted during render, is kept when the navigation completes, androuterchanges identity once per navigation.beforePopStaterejects (it never commits), and not iflocationmoves between the commit and the completion event.vinext:navigateevents carry a stringdetail("vinext.routerStateCommitted"). It is a string, not an object, so the provider recognises events from anynext/routermodule instance (the client entry and page chunks can each evaluate their own). Avinext:navigateevent dispatched outside the router, without thatdetail, still records the live state, as before.tests/e2e/pages-router/shallow-routing.spec.tsrelies on that.getRouterSnapshot()and thenext/navigationcompat hooks are not changed.Behaviour
What the destination page's render sees from
useRouter():<Link>from/first-render-routerto/first-render-router/1, first renderquery {},asPathandpathnameof the previous pagerouter.pushfrom/first-render-router/1to/2(page stays mounted), first renderid: "1"id: "2"/first-render-router/1, first renderid: "2"id: "1"locationmoves after the navigation commits, before React renders and through completionvinext:navigaterouteridentityrouterkeeps its identityThe Next.js column comes from its source (
Router#set()assigning state beforesub(), andAppContainerbuilding the context from that state), not from running a Next.js app.Tests
tests/e2e/pages-router/first-render-router.spec.ts, with new pagestests/fixtures/pages-basic/pages/first-render-router/{index,[id]}.tsx. The[id]page recordsuseRouter()andlocation.pathnameon every client render."returns the new route on the first render after client navigation": every render after a
<Link>click, arouter.pushto another param and a back navigation sees the destination'squery,pathnameandasPath. Onmainit fails on the first step: the first render records{"query":{},"pathname":"/first-render-router","asPath":"/first-render-router","location":"/first-render-router/1"}."keeps the committed route if location moves after the commit": wraps
__VINEXT_ROOT__.renderso the URL changes withhistory.replaceStateright after the push to/2schedules its render, waits untilrouteChangeCompleteand thevinext:navigatelistener have run, and checks that every render saw/first-render-router/2. With a provider that re-reads the live location during render or on completion, a render mixed the moved URL with the committed page (asPath "/first-render-router/1?moved=1",query {id: "1", moved: "1"}). It also fails onmain."treats vinext:navigate from another router instance as committed": moves the URL, then dispatches
vinext:navigatewith the router's marker built outside the provider's module, as a secondnext/routerinstance would, and checks that no render picks up the moved URL. With an object marker compared by identity, the provider took the event as external and renderedasPath "/first-render-router/1?moved=1".Validation
PLAYWRIGHT_PROJECT=pages-router npx playwright test tests/e2e/pages-router/first-render-router.spec.ts --project=pages-router --retries=0: all three tests pass with the fix. Withrouter.tsrestored tomain, the first two fail as described above.PLAYWRIGHT_PROJECT=pages-router npx playwright test tests/e2e/pages-router/first-render-router.spec.ts tests/e2e/pages-router/shallow-routing.spec.ts tests/e2e/pages-router/before-pop-state.spec.ts --project=pages-router --retries=0: 20 passed. An earlier run that also includednavigation.spec.ts: 39 passed (includinghmr.spec.ts, which the config pulls in throughpages-router-isolated; its MDX test failed intermittently in earlier runs, onmaintoo).npx vp test run tests/shims.test.ts: 1483 passed.npx vp check: format, lint and type check pass.